package servlet;

import dao.StarDao;
import dao.StarDaoImpl;
import io.jsonwebtoken.Claims;
import org.json.JSONObject;
import pojo.Star;
import redis.RedisDao;
import redis.RedisDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;

import static util.JwtUtil.parseJWT;
import static util.JwtUtil.validateJWT;

/**
 * @author moyv
 */
public class StarServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token=req.getParameter("token");
        JSONObject objResult=new JSONObject();
        System.out.println(token);
        int result=0;
        if(validateJWT(token)){
            Claims claims=parseJWT(token);
            int account=Integer.parseInt(claims.getId());
            JSONObject obj=new JSONObject(req.getParameter("star"));
            int type=obj.getInt("type");
            int postId=obj.getInt("postId");
            System.out.println(postId);
            Star star=new Star();
            star.setPostId(postId);
            star.setStarAccount(account);
            StarDao dao=new StarDaoImpl();
            RedisDao dao1=new RedisDaoImpl();
            if (type==0){
                star.setStarTime(new Timestamp(System.currentTimeMillis()));
//                查询是否已经点过赞
                if(dao1.queryStar(postId,account)){
                    result=3;
                }else{
                    int starId=dao.addStar(star);
                    star.setStarId(starId);
                    if(dao1.addStar(star)){
//                    点赞成功
                        result=1;
                    }
                }
            }else if (type==1){
                if(dao1.unStar(postId,account)){
//                    取消点赞成功
                    result=2;
                }
            }
        }else {
            System.out.println("令牌有误");
        }
        objResult.put("result",result);
        resp.setContentType("text/json; charset=utf-8");
//        输出数据
        PrintWriter out = resp.getWriter();
        out.print(objResult);
    }
}
